package com.fortune.controller;

import com.faneui.common.bean.BaseResp;
import com.faneui.common.exception.BusinessException;
import com.faneui.common.utils.ListUtils;
import com.fortune.dal.dao.CustDAO;
import com.fortune.dal.model.Cust;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private CustDAO custDAO;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView indexOfAll() throws Exception {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }

    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    @ResponseBody
    public BaseResp doLogin(@RequestBody Cust cust) throws BusinessException {
        BaseResp resp = new BaseResp();
        try {
            // 校验 user 参数是否为空
            if(StringUtils.isBlank(cust.getPhone())) {
                throw new BusinessException("手机号为空") ;
            }
            if(StringUtils.isBlank(cust.getPassword())){
                throw new BusinessException("密码是空");
            }
            // 先检查下 username 是否存在
            Cust param = new Cust();
            param.setPhone(cust.getPhone());
            param.setPassword(cust.getPassword());
            List<Cust> custs = custDAO.queryByModel(param) ;
            if(ListUtils.isEmpty(custs)) {
                throw new BusinessException("手机号或密码错误") ;
            }
            // 将用户放入回话中
            Cust c = custs.get(0) ;
            String key = "user" ;
            httpSession.setAttribute(key,c);
//            List<Object> orders = null ;
        } catch (Exception ex) {
            resp.setSuccess(false);
            resp.setMsg(ex.getMessage());
        }
        return resp;
    }


}
